<template>
  <a-tree-select
    v-model="value"
    :loading="loading"
    :allow-search="allowSearch"
    :allow-clear="allowClear"
    :disabled="disable"
    :data="treeData"
    :placeholder="placeholder"
    :multiple="multiple"
    :tree-check-strictly="treeCheckStrictly"
    :tree-props="{
      defaultExpandAll: !!searchKey,
    }"
    :field-names="{
      key: 'id',
      title: 'name',
      children: 'children',
    }"
    :filter-tree-node="filterTreeNode"
    @search="fetchData"
    @change="handleEmit"
  ></a-tree-select>
</template>

<script lang="ts" setup>
  import { ref, defineProps, defineEmits, watch } from 'vue';
  import { TreeNodeData } from '@arco-design/web-vue/es/tree/interface';
  import useLoading from '@/hooks/loading';
  import { OrgTreeVo, selectNextOrgByParentId } from '@/api/organization';
  import tree from '@/utils/tree';

  const { loading, setLoading } = useLoading();
  const props = defineProps({
    placeholder: {
      type: String,
      default: () => {
        return '请选择组织机构';
      },
    },
    type: {
      type: String,
      default: '',
    },
    multiple: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    pId: {
      type: String,
      default: '',
    },
    allowSearch: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    allowClear: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    disable: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    treeCheckStrictly: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  });
  const emit = defineEmits(['change']);
  const resData = ref<OrgTreeVo[]>([]);
  const treeData = ref<TreeNodeData[]>([]);
  const parentId = ref(props.pId);
  const handleEmit = (val: any) => {
    emit(
      'change',
      props.multiple
        ? resData.value.filter(
            (item) => (val as string[]).findIndex((x) => x === item.id) > -1
          )
        : resData.value.find((item) => item.id === val) || {}
    );
  };
  const value = ref();
  const searchKey = ref();
  const filterTreeNode = (searchValue: string, nodeData: any) => {
    return nodeData;
  };
  const fetchData = async (val = '') => {
    searchKey.value = val;
    setLoading(true);
    try {
      const { data } = await selectNextOrgByParentId(
        parentId.value,
        props.type,
        searchKey.value
      );
      treeData.value = data;
      // tree-selector 没有@select的事件 故只能将树铺平进行查找
      resData.value = tree.flatTreeData(data);
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    } finally {
      setLoading(false);
    }
  };
  watch(
    () => props.pId,
    (n, o) => {
      if (n !== o) {
        parentId.value = n;
        fetchData();
      }
    }
  );

  fetchData();
</script>
